#!/bin/bash
NODETYPE="slave"
NODETYPE=$1

if [ "$NODETYPE" != "slave" ] && [ "$NODETYPE" != "master" ]; then
    echo "NODETYPE:[NODETYPE], not valid. NODETYPE must be master or slave."
    exit -1
fi

#check web only  master
if [ "$NODETYPE" == "master" ]; then
  if [ ! -f ${TARS_INSTALL}/web.tgz ]; then
      echo "no web exits, please copy TarsWeb to ${TARS_INSTALL}/web.tgz first."
      exit -1
  fi
fi

#check framework only master
if [ "$NODETYPE" == "master" ]; then
  if [ ! -f ${TARS_INSTALL}/framework.tgz ]; then
      echo "no framework exits, please copy framework to ${TARS_INSTALL}/framework.tgz first."
      exit -1
  fi
fi

#check node
if [ "$NODETYPE" == "slave" ]; then
  if [ ! -f ${TARS_INSTALL}/node.tgz ]; then
      echo "no node exits, please copy node to ${TARS_INSTALL}/node.tgz first."
      exit -1
  fi
fi

if [ ${MOUNT_DATA} == true ];then
  mkdir -p /data/tarsnode_data && ln -s /data/tarsnode_data ${TARS_INSTALL}/tarsnode/data
fi

echo "tar files web..."
cd ${TARS_INSTALL}
if [ "$NODETYPE" == "master" ]; then
  tar xzfv framework.tgz
  tar xzfv web.tgz
else
  tar xzfv node.tgz
fi

echo "start install..."
if [ -d /root/init ];then
	for x in $(ls /root/init)
	do
		if [ -f /root/init/$x ];then
			chmod 777 /root/init/$x
			/bin/bash /root/init/$x ${NODETYPE}
			#rm -rf /root/init/$x
		fi
	done
fi

if [ "$NODETYPE" == "master" ]; then
  echo "start master node..."
  chmod 777 ${TARS_INSTALL}tars_install.sh
  /bin/bash ${TARS_INSTALL}/tars_install.sh
else
  echo "start slave node..."
  chmod 777 ${TARS_INSTALL}tarsnode_install.sh
  /bin/bash ${TARS_INSTALL}/tarsnode_install.sh
fi

echo "begin check server..."
if [ "$NODETYPE" != "master" ]; then
  TARS=(tarsAdminRegistry tarslog tarspatch tarsconfig tarsnode tarsnotify tarsproperty tarsqueryproperty tarsquerystat tarsregistry tarsstat)
else
  TARS=(tarsnode)
fi

while [ 1 ]
do

  for var in ${TARS[@]};
  do
    PID=`ps -eopid,cmd | grep "$var"|awk '{print $1}'`
    #TODO EXIT
    #if ["$PID" == ""];then
    #  echo "$var is not alive "
    #  exit -1
    #fi
  done

  if [ "$NODETYPE" != "master" ]; then
    pm2 ping tars-node-web; pm2 ping tars-user-system
  fi

  sleep 3

done

